package com.lz.comm.net

import androidx.room.Room
import androidx.room.RoomDatabase
import com.lz.comm.extension.GSON
import com.lz.library.BuildConfig
import com.lz.library.base.Repository
import com.lz.library.extension.APP
import kotlinx.coroutines.Dispatchers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

/**
 *  author: you : 2020/04/31, 适用于固定server
 */
object DataRepository : Repository {
    /**
     * 默认超时时间
     */
    private const val DEF_MILL_TIMEOUT = 10L

    private val retrofit: Retrofit

    init {
        val builder = OkHttpClient.Builder()
            .proxy(Proxy.NO_PROXY)
            .connectTimeout(DEF_MILL_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(DEF_MILL_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(DEF_MILL_TIMEOUT, TimeUnit.SECONDS)


        if (!BuildConfig.isRelease) {
            builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        }

        retrofit = Retrofit.Builder()
            .client(builder.build())
            .addConverterFactory(ScalarsConverterFactory.create()) //增加返回值泛型String类型的支持
            .addConverterFactory(GsonConverterFactory.create(GSON)) //增加返回值泛型Gson类型的支持
            //返回Flow<T>的支持一般使用同步在IO中执行
            .addCallAdapterFactory(FlowCallAdapterFactory.createSynchronous(Dispatchers.IO))
            .baseUrl(BuildConfig.baseUrl)
            .build()
    }

    override fun <T> getService(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    override fun <T : RoomDatabase> getRoomDatabase(databaseClass: Class<T>, dbName: String): T =
        Room.databaseBuilder(APP, databaseClass, dbName).build()
}